<template>
  <div class="chatview">
    <div class="maxdiv">
      <div class="chatApp">
        <div class="chatheader">
          <el-avatar
            :size="50"
            src="http://112.74.185.144:8000/files/ZQI1667437641.png"
          ></el-avatar>
          <div>
            <p>闲小呗</p>
            <span>客服热线9510211</span>
          </div>
        </div>
        <div ref="chatbox" class="chatcontdiv">
          <div @click="getchatinfo()" class="historybtn">查看历史查询记录</div>
          <div
            v-for="(item, index) in msglist"
            :key="index"
            :class="item.senderid == selfobj.userTel ? 'mymsgdiv' : ''"
            class="chat-item-msg"
          >
            <img :src="item.headerphoto" alt="" />
            <div class="msgtxt">
              <span>{{ item.sendername }}</span>
              <div v-if="item.msg" v-html="item.msg" class="msgdiv"></div>
              <div v-if="item.msgimg" class="msgdiv">
                <img :src="item.msgimg" alt="" />
              </div>
            </div>
          </div>
        </div>
        <div class="chatsenddiv">
          <quill-editor
            v-model="content"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
          >
          </quill-editor>
          <el-upload
            id="iviewUp"
            :show-upload-list="false"
            :on-success="handleSuccessQuill"
            :format="['jpg', 'jpeg', 'png', 'gif']"
            name="file"
            :max-size="2048"
            multiple
            :action="uploadRichTextImg"
            style="display: none"
          >
            <Button icon="ios-cloud-upload-outline"></Button>
          </el-upload>
          <el-button
            class="sendbtn"
            type="primary"
            @click="sendmsg()"
            size="mini"
            round
            icon="el-icon-position"
          ></el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import filtering from "../assets/js/filtering";
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import * as Quill from "quill"; // 引入编辑器
import ImageResize from "quill-image-resize-module";
Quill.register("modules/imageResize", ImageResize);
import quillEmoji from "quill-emoji";
import "quill-emoji/dist/quill-emoji.css";
Quill.register("modules/quillEmoji", quillEmoji);

export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      selfobj: "",
      msglist: [],
      sensitiveArr:'',  //敏感词汇
      content: "",
      uploadRichTextImg: "http://112.74.185.144:8000/api/common/uploadfile",
      editorOption: {
        placeholder: "请在这里输入",
        modules: {
          "emoji-toolbar": true,
          "emoji-shortname": true,
          toolbar: {
            container: [
              ["emoji"], //表情包
              ["image"], //上传图片、上传视频
            ],
            handlers: {
              image: function (value) {
                if (value) {
                  console.log("重写了");
                  document.querySelector("#iviewUp input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
              width: "50px",
              height: "50px",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
      },
    };
  },
  sockets: {
    connect() {
      console.log("连接成功");
      this.$socket.emit("login", {
        loginer: sessionStorage.getItem("userTel"),
      });
    },
    disconnect() {
      console.log("断开连接");
    },
    relogin(data) {
      console.log(data, 24);
    },
    message(data) {
      console.log("ws 收到服务器消息", data);
      this.msglist.push(data);
      this.updatescorll();
    },
    messagetip(data) {
      console.log(data, 222);
    },
    linetip(msg) {
      if (this.receiverobj == "root") {
        if (msg.type == "kefu") {
          console.log("有客服了");
          this.receiverobj = msg.id;
          this.$socket.emit("onchat", {
            receiverPhone: this.receiverobj,
          });
          this.msglist.push(msg);
        }
      }
    },

    findcustomer(data) {
      console.log(data);
      let a = {
        msg: data.msg,
        // msgimg: "",
        type: 1,
        senderid: "root",
        sendername: data.userName,
        receiverPhone: this.selfobj.userTel,
        headerphoto: data.headerphoto,
      };
      this.receiverobj = data.senderid;
      this.$socket.emit("onchat", {
        receiverPhone: this.receiverobj,
      });
      this.msglist.push(a);
    },
  },

  methods: {


    //请求跟客服的聊天记录
    getchatinfo() {
      this.$axios({
        url: "api/getkefumsg",
        params: {
          sendid: this.selfobj.userTel,
          type: "user",
        },
      })
        .then((resp) => {
          console.log(resp.data.data, 213);
          resp.data.data.forEach((item) => {
            this.msglist.push({
              msg: item.chatContent,
              msgimg: item.msgimg,
              userName: item.userName,
              senderid: item.sendPhone,
              headerphoto: item.userPhoto,
            });
          });
          this.$nextTick(() => {
            this.updatescorll();
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },

    handleSuccessQuill(res) {
      console.log(res, 152);
      // 获取富文本组件实例
      const quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        const length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.data);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息，需引入Message
        console.log("图片插入失败");
      }
    },
    onEditorReady(editor) {
      // 准备编辑器
      console.log(editor);
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {
      console.log(this.content);
    }, // 内容改变事件
    escapeStringHTML(str) {
      str = str.replace(/&lt;/g, "<");
      str = str.replace(/&gt;/g, ">");
      return str;
    },

    sendmsg() {
      let newmgs = filtering(this.sensitiveArr, this.content);
      let a = {
        msg: newmgs,
        msgimg: "",
        type: 1,
        senderid: this.selfobj.userTel,
        sendername: this.selfobj.userName,
        receiverPhone: this.receiverobj,
        headerphoto: this.selfobj.userPhoto,
      };
      console.log(a);
      this.$socket.emit("send_msg", a);
      this.msglist.push(a);
      this.updatescorll();
      this.content = "";
    },
    updatescorll() {
      let chatbox = this.$refs.chatbox;
      console.log(chatbox);
      this.$nextTick(() => {
        chatbox.scrollTop = chatbox.scrollHeight;
      });
    },
  },
  destroyed() {
    this.$socket.emit("outchat");
  },
  created(){
    document.title = '客服聊天'
  },
  mounted() {
    this.$axios({  //敏感词汇
      url: 'api/sensitiveTable/get',
      method: "GET"
    }).then((data) => {
      console.log(data,451);

      this.sensitiveArr=data.data.data.map((i)=>{
        return i.sensitiveField
      })
      console.log(this.sensitiveArr,457);
    }).catch ((err) => {
      console.log(err);
    })
    console.log(sessionStorage.getItem("userTel"), 210);
    this.$socket.emit("login", {
      loginer: sessionStorage.getItem("userTel"),
    });
    this.$axios
      .get("api/userTabel/userinfo", {
        params: {
          userTel: sessionStorage.getItem("userTel"),
        },
      })
      .then((data) => {
        // console.log(data);
        this.selfobj = data.data.data[0];
      });

    this.$socket.emit("findcustomer", {});
  },
};
</script>

<style scoped>
.chatview {
  width: 100%;
  height: 100vh;
  background: url(https://img.alicdn.com/tfs/TB1C.3nefb2gK0jSZK9XXaEgFXa-2880-2000.jpg)
    0 0 no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}
.maxdiv {
  /* width: 100%; */
  width: 960px;
  height: 650px;
  background-color: rgb(238, 238, 238);
  border-radius: 10px;
}
.chatApp {
  -webkit-tap-highlight-color: transparent;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
    Helvetica Neue, Arial, Noto Sans, sans-serif, Apple Color Emoji,
    Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
  height: 100%;
  line-height: 1.5;
}
.chatheader {
  width: 100%;
  height: 60px;
  border-bottom: 1px solid rgb(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding-left: 30px;
}
.chatheader > div {
  margin-left: 10px;
}
.chatheader > div > p {
  font-size: 20px;
  margin: 0;
  padding: 0;
}
.chatheader > div > span {
  font-size: 12px;
  color: rgb(0, 0, 0, 0.5);
}
.chatcontdiv {
  width: 100%;
  height: 400px;
  overflow-x: hidden;
  /* scrollbar-width: none; */
  box-sizing: border-box;
  padding-left: 10px;
}
.chatcontdiv::-webkit-scrollbar {
  width: 0;
}
.historybtn {
  text-align: center;
  color: #39f;
  margin-top: 10px;
  cursor: pointer;
}

.chat-item-msg {
  width: 100%;
  display: flex;
  margin-bottom: 20px;
}

.chat-item-msg > img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.msgdiv {
  margin-top: 5px;
  background: white;
  padding: 5px;
  border-radius: 5px;
  max-width: 250px;
  width: fit-content;
  box-shadow: 1px 1px 4px 2px #ccc;
  white-space: normal;
  word-break: break-all;
  overflow: hidden;
}
.msgtxt > span {
  color: rgb(0, 0, 0, 0.3);
  font-size: 13px;
}

.mymsgdiv {
  display: block;
  overflow: hidden;
  padding-bottom: 10px;
}

.mymsgdiv > img {
  display: block;
  float: right;
}

.mymsgdiv > .msgtxt {
  text-align: end;
  float: right;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: fit-content;
  margin-right: 10px;
}
.chatsenddiv {
  width: 100%;
  height: 190px;
  position: relative;
}
.sendbtn {
  position: absolute;
  top: 5px;
  right: 5px;
}

.chatview /deep/ .msgdiv img {
  display: inline-block;
  width: 100px;
  height: 100px;
}
.chatview /deep/ .msgdiv p {
  margin: 0;
  padding: 0;
}
.chatview /deep/ #emoji-palette {
  top: -234px !important;
  left: -1px !important;
  max-width: 586px !important;
}
.chatview /deep/ #tab-panel {
  height: 155px;
}
.quill-editor {
  height: 146px;
}
.chatview /deep/ .ql-editor img {
  display: inline-block;
  width: 100px;
  height: 100px;
}
.chatview /deep/ .ql-container,
.ql-snow {
  border: 0 !important;
  border-radius: 10px;
}
.chatview /deep/ .ql-toolbar.ql-snow {
  border-right: 0;
  border-left: 0;
}
/* .sendbtn {
  position: absolute;
  top: 5px;
  right: 5px;
} */
</style>